import React, {PureComponent} from "react";
import {Form, Icon, Input, InputNumber, Modal, notification, Select, Table, Tooltip} from "antd";
import {tableProps} from "../../lib/ui";
import {connect} from "react-redux";
import {hidExportLog, showEditDateAndRemarkModal, queryExportLog, query} from "./actions";
import {saveRemark} from "../zadOrderPayable/actions";
import {getCurrentOrganization, getPrincipal} from "../../lib/identity";

const {Option} = Select;

const EditableContext = React.createContext();

const EditableRow = ({form, index, ...props}) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
    state = {
        editing: false,
    };

    toggleEdit = () => {
        const editing = !this.state.editing;
        this.setState({editing}, () => {
            if (editing) {
                this.input.focus();
            }
        });
    };

    save = e => {
        const {record, handleSave} = this.props;
        this.form.validateFields((error, values) => {
            if (error && error[e.currentTarget.id]) {
                return;
            }
            this.toggleEdit();
            const update = {...record, ...values};
            handleSave(update);
        });
    };

    renderCell = form => {
        this.form = form;
        const {children, dataIndex, record, inputType, options = [], placeholder} = this.props;
        const {editing} = this.state;
        let column;
        if (inputType === "number") {
            column = <InputNumber ref={node => (this.input = node)} onPressEnter={e => this.saveStatus(e, dataIndex)}
                                  onBlur={e => this.saveStatus(e, dataIndex)}/>;
        } else if (inputType === "select") {
            column = <Select placeholder={placeholder} ref={node => (this.input = node)} style={{width: 100}}
                             onChange={e => this.saveStatus(e, dataIndex)} allowClear={true}>
                {options.map((item, index) => (
                    <Option key={index} value={item.value}>
                        {item.label}
                    </Option>
                ))}
            </Select>;
        } else {
            column = <Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}/>;
        }
        return editing ? (
            <Form.Item style={{margin: 0}}>
                {form.getFieldDecorator(dataIndex, {
                    initialValue: record[dataIndex],
                })(column)}
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{paddingRight: 24}}
                onClick={this.toggleEdit}
            >
                {children}
            </div>
        );
    };

    render() {
        const {
            editable,
            dataIndex,
            title,
            record,
            index,
            inputType,
            handleSave,
            showTip,
            admin,
            children,
            valueField,
            labelField,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editable ? (
                    <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
                ) : (
                    children
                )}
            </td>
        );
    }
}

class ExportLogModal extends PureComponent {

    state = {rowId: ""};
    // 选中行
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    rowId: record.id,
                });
            },
        };
    };

    setRowClassName = (record) => {
        return record.id === this.state.rowId ? 'clickRowStyl editable-row' : 'editable-row';
    }

    handleSave = row => {
        const {dispatch} = this.props;
        dispatch(saveRemark(row)).then(action => {
            if (action.error !== true) {
                notification.success({
                    message: '修改成功'
                });
                dispatch(queryExportLog());
            }
        });
    };

    handleCancel = () => {
        const {dispatch} = this.props;
        dispatch(hidExportLog());
        dispatch(query({
            "userId": getPrincipal().id,
            "organizationId": getCurrentOrganization()
        }));
    };

    handleDownload = fileName => {
        window.location.href = "/file/" + fileName;
    };

    changeInvoiceDate = record => {
        const {dispatch} = this.props;
        dispatch(showEditDateAndRemarkModal({logId: record.id, field: "invoiceDate"}));
    };

    changeSettlementDate = record => {
        const {dispatch} = this.props;
        dispatch(showEditDateAndRemarkModal({logId: record.id, field: "settlementDate"}));
    };


    render() {
        const {dataSource, visible, loading} = this.props;
        const columns = [
            {
                title: "下载时间",
                dataIndex: "downloadTime",
                width: "180px",
            }, {
                title: "转换币种/汇率",
                dataIndex: "currency",
                width: "180px",
            }, {
                title: "下载列",
                dataIndex: "columns",
                width: "280px",
                ellipsis: true,
                render: text => <Tooltip placement="left" title={text}>{text}</Tooltip>
            }, {
                title: "文件名",
                width: "220px",
                dataIndex: "fileName",
                render: (text) => <span>
                    <a onClick={() => this.handleDownload(text)}>{text}</a>
                </span>
            }, {
                title: "开票日期",
                dataIndex: "invoiceDate",
                width: "150px",
                render: (text, record) => (
                    <span>{text} <Icon onClick={() => this.changeInvoiceDate(record)} type="edit"/></span>)
            }, {
                title: "结算日期",
                dataIndex: "settlementDate",
                width: "150px",
                render: (text, record) => (
                    <span>{text} <Icon onClick={() => this.changeSettlementDate(record)} type="edit"/></span>)
            }, {
                title: "备注",
                dataIndex: "remark",
                editable: true
            }
        ];

        const editColumns = columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    options: col.options,
                    placeholder: col.placeholder,
                    inputType: col.inputType,
                    handleSave: this.handleSave
                }),
            };
        });

        const components = {
            body: {
                row: EditableFormRow,
                cell: EditableCell,
            },
        };

        return (

            <Modal
                title="历史下载记录"
                visible={visible}
                onCancel={this.handleCancel}
                confirmLoading={loading}
                footer={null}
                width="90%"
            >
                <Table
                    {...tableProps}
                    scroll={{x: 1500}}
                    columns={editColumns}
                    dataSource={dataSource}
                    onRow={this.onClickRow}
                    loading={loading}
                    components={components}
                    rowClassName={this.setRowClassName}
                />
                <form
                    id="exportByFileId"
                    method="post"
                    target="_blank"
                    action="/api/zadOrder/download"
                >
                    <input
                        id="fileName"
                        name="fileName"
                        type="hidden"
                    />
                </form>
            </Modal>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.zadOrderReceivable.exportLogList
    };
};

export default connect(mapStateToProps)(ExportLogModal);
